package com.example.base.tools

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.widget.Toast
import androidx.core.content.FileProvider
import com.example.base.BaseApp
import java.io.File
import java.util.*

/**  系统 API 工具  **/
object SystemApiTool {

    private var mContext: Context? = null

    fun init(context: Context) {
        mContext = context
    }

    /**
     * 调用系统的打开方式来打开文件
     * @param file 目标打开文件
     * @param unSupportCallback 不支持目标文件类型时的回调
     */
    fun openFile(file: File, unSupportCallback: () -> Unit) {
        try {
            if (file.isDirectory) {
                unSupportCallback()
                return
            }

            // 预备 预览类型的 Intent
            val intent = Intent("android.intent.action.VIEW")
            intent.addCategory("android.intent.category.DEFAULT")
            // intent.addCategory(Intent.CATEGORY_OPENABLE)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION)
            val uri = parseFileUri(file)

            // 解析并获取文件预览类型
            val dataType = parseDataType(file)
            if (dataType.isEmpty()) {
                unSupportCallback()
                return
            }
            intent.setDataAndType(uri, dataType)

            mContext?.startActivity(intent)
        }catch (e: Exception){
            Toast.makeText(mContext, "暂不支持打开", Toast.LENGTH_LONG).show()

        }

    }

    /**  兼容 7.0+ Uri  **/
    private fun parseFileUri(file: File): Uri {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //设置7.0以上共享文件，分享路径定义在xml/file_paths.xml
            FileProvider.getUriForFile(
                BaseApp.context,
                "${BaseApp.context.applicationInfo.packageName}.fileProvider",
                file
            )
        } else {
            // 7.0以下,共享文件
            Uri.fromFile(file)
        }
    }

    /**  根据 file 来解析数据类型字段, 不支持时则返回空串  **/
    private fun parseDataType(file: File): String {
        val fileName = file.name.toLowerCase(Locale.getDefault())
        return when (fileName.substring(fileName.lastIndexOf(".") + 1)) {
            "pdf" -> "application/pdf"
            "doc", "docx" -> "application/msword"
            "ppt", "pptx" -> "application/vnd.ms-powerpoint"
            "xls", "xlsx" -> "application/vnd.ms-excel"
            "jpg", "jpeg", "bmp", "png", "gif" -> "image/*"
            "txt" -> "text/plain"
            "mp4", "flv", "avi" -> "video/*"
            "apk" -> "application/vnd.android.package-archive"
            "chm" -> "application/x-chm"
            "mp3", "m4a" -> "audio/*"
            else -> ""
        }
    }

}